package com.jisu.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jisu.common.ResultVo;
import com.jisu.dto.AdminDTO;
import com.jisu.dto.LoginRequest;
import com.jisu.mapper.AdminMapper;
import com.jisu.pojo.Admin;
import com.jisu.service.IAdminService;
import com.jisu.utils.JWTUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final AdminMapper adminMapper;

    public AdminServiceImpl(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    @Override
    public ResultVo<String> login(LoginRequest loginRequest) {
        if (loginRequest == null || StringUtils.isBlank(loginRequest.getAccount())
                || StringUtils.isBlank(loginRequest.getPassword())) {
            return ResultVo.fail("账号和密码不能为空");
        }

        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAccount, loginRequest.getAccount());
        Admin admin = adminMapper.selectOne(wrapper);

        if (admin == null) {
            return ResultVo.fail("账号不存在",200);
        }

        if (!loginRequest.getPassword().equals(admin.getPassword())) {
            return ResultVo.fail("密码错误",201);
        }

        // 更新最后登录时间
        admin.setLastLoginTime(LocalDateTime.now());
        adminMapper.updateById(admin);

        // 生成JWT令牌
        Map<String, String> payload = new HashMap<>();
        payload.put("adminId", admin.getAdminId().toString());
        payload.put("account", admin.getAccount());
        payload.put("permissions", admin.getPermissions().toString());

        String token = JWTUtil.getToken(payload);
        return ResultVo.success("登录成功", token);
    }


    @Override
    public ResultVo<Admin> addAdmin(Admin admin) {
        if(admin== null){
            return ResultVo.fail("管理员信息不能为空");
        }

        adminMapper.insert(admin);
        return ResultVo.success("添加成功",admin);
    }

    @Override
    public ResultVo deleteAdmin(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return ResultVo.fail("ID列表不能为空");
        }

        int rows = adminMapper.deleteBatchIds(ids); // 使用MyBatis-Plus内置方法
        return rows > 0 ?
                ResultVo.success("删除成功，影响行数: " + rows) :
                ResultVo.fail("删除失败，ID不存在");
    }

    @Override
    public ResultVo updateAdmin(Admin admin) {
        if (admin.getAdminId() == null) {
            return ResultVo.fail("更新失败，管理员ID不能为空");
        }
        admin.setUpdatedTime(LocalDateTime.now());
        int rows = adminMapper.updateById(admin);

        if (rows == 0) {
            return ResultVo.fail("更新失败，未找到对应管理员");
        } else {
            Admin updatedAdmin = adminMapper.selectById(admin.getAdminId());
            return ResultVo.success("更新成功", updatedAdmin);
        }
    }

    @Override
    public ResultVo<IPage<Admin>> getAdminInPage(AdminDTO adminDTO) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();

        if (adminDTO != null) {
            wrapper.eq(adminDTO.getAdminId()!= null, Admin::getAdminId, adminDTO.getAdminId());
            wrapper.like(StringUtils.isNotBlank(adminDTO.getAccount()), Admin::getAccount, adminDTO.getAccount());
            wrapper.like(StringUtils.isNotBlank(adminDTO.getRealName()), Admin::getRealName, adminDTO.getRealName());
            wrapper.like(StringUtils.isNotBlank(adminDTO.getPhone()), Admin::getPhone, adminDTO.getPhone());
            wrapper.eq(adminDTO.getGender() != null, Admin::getGender, adminDTO.getGender());
            wrapper.eq(adminDTO.getStatus() != null, Admin::getStatus, adminDTO.getStatus());
            wrapper.eq(adminDTO.getPermissions()!= null, Admin::getPermissions, adminDTO.getPermissions());
        }

        Page<Admin> page = new Page<>(adminDTO.getPageNum(), adminDTO.getPageSize());
        return ResultVo.success("查询成功",adminMapper.selectPage(page, wrapper));
    }

}
